#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/shm.h>

#include "alg.8-0-shmdata.h"

int main(int argc, char *argv[])
{
    void *shmptr = NULL;
    struct shared_struct *shared;
    int shmid;
    key_t key;
 
    sscanf(argv[1], "%x", &key);
    printf("%*sshmread: IPC key = %x\n", 30, " ", key);
    
    shmid = shmget((key_t)key, sizeof(int) * 2 + TEXT_NUM*sizeof(struct shared_struct), 0666|PERM);
    if (shmid == -1) {
        ERR_EXIT("shread: shmget()");
    }

    shmptr = shmat(shmid, 0, 0);
    if(shmptr == (void *)-1) {
        ERR_EXIT("shread: shmat()");
    }
    printf("%*sshmread: shmid = %d\n", 30, " ", shmid);    
    printf("%*sshmread: shared memory attached at %p\n", 30, " ", shmptr);
    printf("%*sshmread process ready ...\n", 30, " ");
    
    int *tail_ptr = (int *) shmptr;
    int *head_ptr = tail_ptr + 1;
    shmptr += 8;

    shared = (struct shared_struct *)shmptr;
    
    struct shared_struct * start_ptr = shared;
    printf("%p %p %p", tail_ptr, head_ptr, shmptr);

    while (1) {
        int flag = 0;
        while ((*tail_ptr + 1) % TEXT_NUM != *head_ptr) {
            sleep(1); /* message not ready, waiting ... */
        }
        while(*head_ptr != *tail_ptr)
        {
            start_ptr = shared+ *head_ptr;
            printf("%*sYour name: %s\n", 30, " ", start_ptr->student_name);
            if(strncmp(start_ptr->student_name, "end", 3) == 0) {
                
                flag = 1;
                break;
            }
            
            printf("%*sYour id: %s\n", 30, " ", start_ptr->student_id);
            (*head_ptr)  = (*head_ptr + 1) % TEXT_NUM;
            printf("%d ", *head_ptr);
            printf("%d\n", *tail_ptr);
        }

        if(flag){
            break;
        }
    } /* it is not reliable to use shared->written for process synchronization */
     
   if (shmdt(shmptr-8) == -1) {
        ERR_EXIT("shmread: shmdt()");
   } 
    sleep(1);
    exit(EXIT_SUCCESS);
}
